﻿using DroidClaim.Service.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Device.Location;

namespace DroidClaim.BL.Helper
{
    public class ClosestSurveyor
    {
        private List<SurveyorDto> surveyorList;
        public ClosestSurveyor(List<SurveyorDto> surveyorList)
        {
            this.surveyorList = surveyorList;
        }

        public List<SurveyorDto> GetClosest(double latitude, double longitude)
        {
            List<SurveyorDto> result = new List<SurveyorDto>();
            try
            {
                if(surveyorList.Count<=0){
                    throw new Exception("empty surveyor");
                }

                //GeoCoordinate customerLocation = new GeoCoordinate(latitude, longitude);

                //GeoCoordinate surveyorLocation = new GeoCoordinate(surveyorList[0].SurveyorLocation.Latitude, surveyorList[0].SurveyorLocation.Longitude);
                //double minDistance = customerLocation.GetDistanceTo(surveyorLocation);
                //minDistance = Math.Abs(minDistance);
                //SurveyorDto minSurveyor = surveyorList[0];
                double minDistance = -1;
                SurveyorDto minSurveyor = null;
                foreach (SurveyorDto surveyor in surveyorList)
                {
                    if (surveyor.SurveyorLocation != null)
                    {
                        GeoCoordinate location = new GeoCoordinate(surveyor.SurveyorLocation.Latitude, surveyor.SurveyorLocation.Longitude);
                        double distance = location.GetDistanceTo(location);
                        distance = Math.Abs(distance);
                        if (minDistance < 0)
                        {
                            minSurveyor = surveyor;
                            minDistance = distance;
                        }
                        else
                        {
                            double resultCalculate = distance - minDistance;
                            if (resultCalculate < 0)
                            {
                                minDistance = distance;
                                minSurveyor = surveyor;
                            }
                        }
                    }
                }
                result.Add(minSurveyor);
            }
            catch (Exception ex)
            {
            }

            return result;
        }
    }
}